const app = getApp();

Page({
  data: {
    isAuthorized: false,
    userInfo: null,
    userCondition: '',
    showEditModal: false
  },

  onLoad: function () {
    this.checkAuthStatus();
  },

  onShow: function () {
    this.checkAuthStatus();
  },

  // 检查授权状态
  checkAuthStatus: function () {
    const isAuthorized = app.globalData.isAuthorized;
    const userInfo = app.globalData.userInfo;
    const userCondition = wx.getStorageSync('userCondition') || '';

    this.setData({
      isAuthorized,
      userInfo,
      userCondition
    });
  },

  // 处理用户登录
  handleUserLogin: function () {
    wx.showLoading({
      title: '登录中...'
    });

    app.userLogin().then((userInfo) => {
      wx.hideLoading();
      this.setData({
        isAuthorized: true,
        userInfo: userInfo
      });
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    }).catch((err) => {
      wx.hideLoading();
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
      console.error('登录失败:', err);
    });
  },

  // 编辑用户信息
  editUserInfo: function () {
    this.setData({
      showEditModal: true
    });
  },

  // 关闭编辑弹窗
  closeEditModal: function () {
    this.setData({
      showEditModal: false
    });
  },

  // 病情输入
  onConditionInput: function (e) {
    this.setData({
      userCondition: e.detail.value
    });
  },

  // 保存用户病情
  saveUserCondition: function () {
    const userCondition = this.data.userCondition;
    wx.setStorageSync('userCondition', userCondition);

    this.setData({
      showEditModal: false
    });

    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
  },

  // 跳转到用药记录
  goToMedicalRecord: function () {
    wx.switchTab({
      url: '/pages/record/index'
    });
  },

  // 跳转到视频页面
  goToVideo: function () {
    wx.switchTab({
      url: '/pages/video/index'
    });
  },

  // 前往协议
  goToAgreement() {
    wx.navigateTo({ url: '/pages/agreement/agreement' });
  },

  // 前往登录
  goToLogin() {
    wx.navigateTo({ url: '/pages/login/index' });
  },

  // 跳转到设置页面
  goToSettings: function () {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 退出登录
  handleLogout: function () {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.logout();
          this.setData({
            isAuthorized: false,
            userInfo: null,
            userCondition: ''
          });
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 阻止事件冒泡
  noop: function () {}
});

